package com.time.company.components.profile;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.base.BaseActivity;
import com.time.company.base.BasePW;
import com.time.company.components.popup.DeletePW;
import com.time.company.components.popup.ExitEditPW;
import com.time.company.servermodel.BasicBean;
import com.time.company.servermodel.profile.Feedback;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ScreenUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.views.MyGridView;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.helper.picasso.PicassoImageLoader;
import com.time.company.webserver.listener.ResponseCallback;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.ProfileParameters;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;
import com.yanzhenjie.nohttp.BasicBinary;
import com.yanzhenjie.nohttp.Binary;
import com.yanzhenjie.nohttp.FileBinary;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


/**
 * 意见反馈
 * Created by Bing on 2017/10/17.
 * E-mail is tx16bing@163.com
 */

public class FeedBackActivity extends BaseActivity implements View.OnClickListener {

    // Views
    private LinearLayout llParent;
    private ImageView ivBack;
    private TextView tvRelease;
    private EditText etContent;
    private GridView gvPic;

    // 窗口背景属性
    private WindowManager.LayoutParams attributes;
    private ExitEditPW exitEditPW;
    private DeletePW deletePW;
    private GridPicAdapter mPicAdapter;
    public static ArrayList<AlbumFile> mAlbumFiles = new ArrayList<>();

    public static void start(Activity mContext) {
        Intent intent = new Intent(mContext, FeedBackActivity.class);
        mContext.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed_back);
        assignViews();
        initAdapter();
    }

    private void assignViews() {
        llParent = findView(R.id.ll_parent);
        ivBack = findView(R.id.iv_back);
        tvRelease = findView(R.id.tv_release);
        etContent = findView(R.id.et_feedback_content);
        gvPic = findView(R.id.gv_feedback_pics);

        ivBack.setOnClickListener(this);
        tvRelease.setOnClickListener(this);
    }

    private void initAdapter() {
        mPicAdapter = new GridPicAdapter(this);
        mPicAdapter.updateData(mAlbumFiles);
        gvPic.setAdapter(mPicAdapter);
        gvPic.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                if (position == mAlbumFiles.size()) {
                    chooseAlbum();

                } else {
                    galleryAlbum(position);
                }
            }
        });
    }

    /**
     * 浏览
     *
     * @param position
     */
    private void galleryAlbum(int position) {
        Album.galleryAlbum(FeedBackActivity.this)
                .requestCode(2) // 请求码，会在listener中返回。
                .checkedList(mAlbumFiles) // 要浏览的图片列表：ArrayList<String>。
                .navigationAlpha(80) // Android5.0+的虚拟导航栏的透明度。
                .checkable(true) // 是否有浏览时的选择功能。
                .currentPosition(position)
                .widget(Widget.newLightBuilder(FeedBackActivity.this)
                        .title("已选")
                        .mediaItemCheckSelector(Color.WHITE, Color.GREEN) // 图片或者视频选择框的选择器。
                        .bucketItemCheckSelector(
                                ContextCompat.getColor(application, R.color.colorPrimary),
                                ContextCompat.getColor(application, R.color.colorPrimary)) // 切换文件夹时文件夹选择框的选择器。
                        .build())
                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                        if (null != result) {
                            mAlbumFiles = result;
                            mPicAdapter.updateData(mAlbumFiles);
                        }
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(int requestCode, @NonNull String result) {
                        // 用户取消了操作。
                    }
                })
                .start();
    }

    /**
     * 照片
     */
    private void chooseAlbum() {
        Album.image(FeedBackActivity.this)
                .multipleChoice()
                .requestCode(200)
                .camera(true)
                .columnCount(3)
                .selectCount(3)
                .checkedList(mAlbumFiles)
                .widget(Widget.newDarkBuilder(FeedBackActivity.this)
                        .title("图片")
                        .statusBarColor(ContextCompat.getColor(application, R.color.colorPrimary))
                        .toolBarColor(ContextCompat.getColor(application, R.color.colorPrimary))
                        .navigationBarColor(ContextCompat.getColor(application, android.R.color.black)) // Android5.0+的虚拟导航栏颜色。
                        .mediaItemCheckSelector(Color.WHITE, Color.GREEN) // 图片或者视频选择框的选择器。
                        .bucketItemCheckSelector(
                                ContextCompat.getColor(application, R.color.colorPrimary),
                                ContextCompat.getColor(application, R.color.colorPrimary)) // 切换文件夹时文件夹选择框的选择器。
                        .build())

                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                        if (null != result) {
                            mAlbumFiles = result;
                            mPicAdapter.updateData(mAlbumFiles);
                        }
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(int requestCode, @NonNull String result) {
                    }
                })

                .start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                launchExit();
                break;

            case R.id.tv_release:
                // 发布反馈建议
                if (NetWorkUtils.isNetAvailable(this)) {
                    String content = etContent.getText().toString().trim();

                    if (TextUtils.isEmpty(content)) {
                        ToastUtils.showShort(getString(R.string.please_write_your_content));
                        return;
                    }

                    sendRequest(content);

                } else {
                    ToastUtils.showShort(getString(R.string.network_error));
                }
                break;

            default:
                break;
        }
    }

    // 提交建议
    private void sendRequest(String content) {
        ProfileParameters parameters = new ProfileParameters();
        parameters.setCommand(getString(R.string.command_sendFeedBack));
        parameters.setPlatform(getString(R.string.platform_android));
        parameters.setUserId(application.getAccount());
        parameters.setContent(content);
        String url;
        try {
            url = new StringBuilder().append(AddressManager.getInstance().getAddress())
                    .append("?").append(getString(R.string.command))
                    .append("=").append(parameters.getCommand())
                    .append("&").append(getString(R.string.data))
                    .append("=").append(URLEncoder.encode(new Gson().toJson(parameters), "UTF-8"))
                    .toString();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        Request request = NoHttp.createStringRequest(url, RequestMethod.POST);
//            request.setContentType("multipart/form-data; boundary=alamofire.boundary.8479ba3fabe53e37");
        request.add(getString(R.string.command), parameters.getCommand());
        request.add(getString(R.string.platform), parameters.getPlatform());
        request.add("userId", parameters.getUserId());
        request.add("content", parameters.getContent());
        if (mAlbumFiles.size() > 0) {
            List<Binary> binaries = new ArrayList<>();
            for (AlbumFile album : mAlbumFiles) {
                File file = new File(album.getPath());
                BasicBinary fileBinary = new FileBinary(file);
                binaries.add(fileBinary);
            }
            request.add("picFileBinary", binaries);
        }
        request.setCancelSign(toString());
        WebServerManager.getInstance().add(this, request, new ResponseCallback<String>() {
            @Override
            public void onSucceed(int what, Response<String> response) {
                String bean = response.get();
                BasicBean basicBean = new Gson().fromJson(bean, BasicBean.class);

                if (basicBean == null) {
                    return;
                }

                if (basicBean.isSuccess()) {
                    ToastUtils.showShort("平台已收到您的反馈");
                    if (null != mAlbumFiles) {
                        mAlbumFiles.clear();
                    }
                    finish();
                } else {
                    ToastUtils.showShort("反馈失败");
                }
            }

            @Override
            public void onFailed(int what, Object tag, Exception exception, long networkMillis) {

            }
        }, 100, true, true, true);
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (what == 1) {
            if (basicBean != null && basicBean.isSuccess()) {
                finish();
            }
            ToastUtils.showShort(basicBean.getMsg());
        }
    }

    class GridPicAdapter extends BaseAdapter {

        private Context mContext;
        private LayoutInflater mInflater;
        private List<AlbumFile> myAlbums;

        public GridPicAdapter(Context context) {
            mContext = context;
            mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public void updateData(List<AlbumFile> albums) {
            if (albums == null) {
                myAlbums = new ArrayList<>();
            } else {
                myAlbums = albums;
            }
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            if (myAlbums.size() == 3) {
                return 3;
            }
            return (myAlbums.size() + 1);
        }

        @Override
        public AlbumFile getItem(int position) {
            return myAlbums.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.item_pic_grid, parent, false);
                holder.ivPic = (ImageView) convertView.findViewById(R.id.iv_publish_grid_pic);
                holder.ivDelete = (ImageView) convertView.findViewById(R.id.iv_publish_grid_pic_delete);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (((MyGridView) parent).isOnMeasure) {
                return convertView;
            }

            if (position == myAlbums.size()) {
                // 表示最后一个元素
                holder.ivPic.setImageResource(R.drawable.iv_publish_add_pic);
                holder.ivDelete.setVisibility(View.GONE);
                if (position == 3) {
                    holder.ivPic.setVisibility(View.GONE);
                }
            } else {
                int size = ScreenUtils.dip2px(77);
                PicassoImageLoader.loadImageViewSize(mContext,
                        getItem(position).getPath(),
                        size,
                        size,
                        R.drawable.iv_default_92_68,
                        R.drawable.iv_default_92_68,
                        toString(), holder.ivPic);
                holder.ivDelete.setVisibility(View.VISIBLE);
            }

            holder.ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (deletePW == null || !deletePW.isShowing()) {
                        launchDelete(position + "");
                    } else {
                        return;
                    }
                }
            });

            return convertView;
        }

        class ViewHolder {

            ImageView ivPic, ivDelete;
        }

    }

    private void launchExit() {
        final Window window = this.getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        exitEditPW = new ExitEditPW(this, llParent);
        exitEditPW.setTip("退出此次编辑？");
        exitEditPW.setLeft(getString(R.string.btn_think_about));
        exitEditPW.setRight(getString(R.string.btn_confirm));
        exitEditPW.setOnItemClickListener(new BasePW.OnItemClickListener<String>() {
            @Override
            public void onItemClick(int type, String result) {
                finish();
            }
        });
        exitEditPW.showAtLocation(llParent, Gravity.CENTER, 0, 0);
        exitEditPW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    private void launchDelete(String deleteId) {
        final Window window = this.getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        deletePW = new DeletePW(this, llParent, deleteId, getString(R.string.pw_delete_pic_title));
        deletePW.setOnItemClickListener(new BasePW.OnItemClickListener<String>() {
            @Override
            public void onItemClick(int type, String deleteId) {
                // 删除图片
                if (Integer.parseInt(deleteId) >= 0) {
                    mAlbumFiles.remove(Integer.parseInt(deleteId));
                    ToastUtils.showShort(R.string.delete_success);
                    mPicAdapter.updateData(mAlbumFiles);
                }
            }
        });
        deletePW.showAtLocation(llParent, Gravity.CENTER, 0, 0);
        deletePW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    @Override
    public void onBackPressed() {
        launchExit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mAlbumFiles) {
            mAlbumFiles.clear();
        }

        if (null != exitEditPW) {
            exitEditPW.dismiss();
            exitEditPW = null;
        }
    }
}
